import { _decorator, AnimationClip,Animation, Component, Node, SpriteFrame } from 'cc';
import { FSM_PARAMS_TYPE_ENUM, PARAME_NAME_ENUM} from '../../Enums';
import State from '../../Base/State';
import { getInitParamsNumber, getInitParamsTrigger, StateMachine } from '../../Base/StateMachine';
import IdleSubStateMachine from './IdleSubStateMachine';
import TurnLeftSubStateMachine from './TurnLeftSubStateMachine';

const { ccclass, property } = _decorator;



@ccclass('PlayerStateMachine')
export class PlayerStateMachine extends StateMachine {

  async init(){
    this.animationComponent = this.addComponent(Animation)

    this.initParams()
    this.initStateMachines()
    this.initAnimationEvent()
    await Promise.all(this.waitingList)
  }
  //让动画变回idle初始时候
  initAnimationEvent() {
    this.animationComponent.on(
      Animation.EventType.FINISHED,()=>{
        const name = this.animationComponent.defaultClip.name
        const whiteList = ['turn']
        if(whiteList.some(v => name.includes(v))){
          this.setParams(PARAME_NAME_ENUM.IDLE,true)
        }
      }
    )
  }
  initParams() {
    this.params.set(PARAME_NAME_ENUM.IDLE,getInitParamsTrigger())
    this.params.set(PARAME_NAME_ENUM.TURN_LEFT,getInitParamsTrigger())
    this.params.set(PARAME_NAME_ENUM.DIRECTION,getInitParamsNumber())
  }
  initStateMachines() {
     this.stateMachine.set(PARAME_NAME_ENUM.IDLE,new IdleSubStateMachine(this))
     this.stateMachine.set(PARAME_NAME_ENUM.TURN_LEFT,new TurnLeftSubStateMachine(this))
  }

  run(){
    switch(this.currentState){
      case this.stateMachine.get(PARAME_NAME_ENUM.TURN_LEFT):
      case this.stateMachine.get(PARAME_NAME_ENUM.IDLE):
        if(this.params.get(PARAME_NAME_ENUM.TURN_LEFT).value){
          this.currentState =this.stateMachine.get(PARAME_NAME_ENUM.TURN_LEFT)
        }else if(this.params.get(PARAME_NAME_ENUM.IDLE).value){
          this.currentState  =this.stateMachine.get(PARAME_NAME_ENUM.IDLE)
        }else{
          this.currentState =this.currentState
        }
        break;
        default:
          this.currentState =this.stateMachine.get(PARAME_NAME_ENUM.IDLE)
    }
  }
}

